package main

import (
	"context"
	"fmt"
	"sync"
	"time"
)

var wg sync.WaitGroup

func worker(ctx context.Context) {
	go worker2(ctx)
LOOP:
	for {
		fmt.Println("worker")
		time.Sleep(time.Second)
		select {
		case <-ctx.Done():
			break LOOP
		default:
		}
	}
	wg.Done()
}

func worker2(ctx context.Context) {
LOOP:
	for {
		fmt.Println("worker2")
		time.Sleep(time.Second)
		select {
		case <-ctx.Done(): // 等待上级通知
			break LOOP
		default:
		}
	}
}
func main() {
	//context.Background()主要用于main函数，作为context树结构的顶点
	//ctx, cancel := context.WithCancel(context.Background())	//返回done的通道和取消方法
	//wg.Add(1)
	//go worker(ctx)
	//time.Sleep(time.Second * 3)
	//cancel() //通知goroutine结束
	//wg.Wait()
	//fmt.Println("over")

	ctx, cancel := context.WithCancel(context.Background())
	defer cancel()
	for n := range gen(ctx) {
		fmt.Println(n)
		if n == 5 {
			break
		}
	}

}

func gen(ctx context.Context) <-chan int {
	dst := make(chan int)
	n := 1
	go func() {
		for true {
			select {
			case <-ctx.Done():
				return
			case dst<-n:
				n++
			}
		}
	}()
	return dst
}